package com.example.myshools.Activities;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.myshools.R;
import com.example.myshools.entity.Activities;
import com.example.myshools.entity.Constant;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NewFragment extends Fragment {
    private ListView listView;
    private OkHttpClient okHttpClient;
    private List<Activities> AcList=new ArrayList<>();
    private int num=0;
    private int userId=1;
    private int onLoad=0;//是否是上拉加载
    private ActivitiesItemAdapter itemAdapter;
    private int schoolId;//学校id
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View newView = inflater.inflate(R.layout.new_fragment, container, false);
        return newView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        listView = getActivity().findViewById(R.id.list_content);
        okHttpClient = new OkHttpClient();
        //获取学校id
        schoolId=getActivity().getSharedPreferences("school", Context.MODE_PRIVATE).getInt("schoolId",1);

        itemAdapter = new ActivitiesItemAdapter(getContext(), AcList, R.layout.list_content_item);
        listView.setAdapter(itemAdapter);
        initData();
        RefreshLayout refreshLayout = getActivity().findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                onLoad=0;
                num=0;
                initData();
                refreshlayout.finishRefresh(2000);///*,false*/传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                onLoad=1;
                num=num+1;
                initData();
                refreshlayout.finishLoadMore(2000);///*,false*/传入false表示加载失败
            }
        });
    }
    private void initData() {
        FormBody body=new FormBody.Builder().add("num", String.valueOf(num)).add("userId", String.valueOf(userId)).add("schoolId", String.valueOf(schoolId)).build();
        final Request request = new
                Request.Builder().url(Constant.url + "activities/findAll").post(body).build();
        final Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("de===", "连接失败！！！！！！！");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("ss", string.toString());
                Message message = new Message();
                message.what = 1;
                message.obj = string;
                handler.sendMessage(message);
            }
        });
    }
    private void upload() {
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {

            if (msg.what == 1) {
                Gson gson = new GsonBuilder().serializeNulls().create();
                List<Activities> list = gson.fromJson(msg.obj.toString(), new TypeToken<List<Activities>>() {
                }.getType());
                if(onLoad==1){//上拉加载更多
                    for(int i=0;i<list.size();i++){
                        AcList.add(list.get(i));
                    }
                   /* ActivitiesItemAdapter itemAdapter = new ActivitiesItemAdapter(getContext(), AcList, R.layout.list_content_item);
                    listView.setAdapter(itemAdapter);*/
                   itemAdapter.notifyDataSetChanged();
                }else {
                    AcList.clear();//下拉刷新
                    for(int i=0;i<list.size();i++){
                        AcList.add(i,list.get(i));
                    }
                  /*  ActivitiesItemAdapter itemAdapter = new ActivitiesItemAdapter(getContext(), AcList, R.layout.list_content_item);
                    listView.setAdapter(itemAdapter);*/
                    itemAdapter.notifyDataSetChanged();
                }
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

